package itsm.isperp.module.controller.incident;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseProcessController;
import itsm.isperp.framework.web.domain.CountQuery;
import itsm.isperp.framework.web.request.JqGridFilter;
import itsm.isperp.framework.web.request.JqGridFilterRule;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.JqGridResponse;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.project.ProjectDomain;
import itsm.isperp.module.dto.project.ProjectDomain.ProjectDomainType;
import itsm.isperp.module.dto.solr.SolrIcdIncidentDTO;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.incident.IcdCategory;
import itsm.isperp.module.entity.incident.IcdIncident;
import itsm.isperp.module.entity.incident.IcdIncidentHandleProcess;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.entity.serviceCatalog.SrcService;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.incident.IcdCategoryRelamembersService;
import itsm.isperp.module.service.incident.IcdIncidentHandleProcessService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.project.ProjCostTemplateService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.serviceCatalog.SrcServiceService;
import itsm.isperp.module.service.slm.SlmServiceAgreementService;
import itsm.isperp.module.service.sparepart.SptSparepartService;
import itsm.isperp.module.service.wechat.WechatChatService;
import itsm.isperp.module.utils.ProjectDomainUtils;
import itsm.isperp.workflow.service.BpmProcessRunService;
import itsm.isperp.workflow.utils.BpmConst;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 事件管理控制器
 * 
 * @author lizx
 * @date 2013-4-14
 * @since 1.0
 */
@Controller
@RequestMapping("incident/incident")
public class IcdIncidentController extends BaseProcessController<IcdIncident> {

  @Autowired
  protected IcdIncidentService icdIncidentService;

  @Autowired
  protected AppDictService appDictService;

  @Autowired
  protected AppUserService appUserService;

  @Autowired
  protected ProjProjectService projProjectService;

  @Autowired
  protected BpmProcessRunService bpmProcessRunService;

  @Autowired
  protected ProjCostTemplateService projCostTemplateService;

  @Autowired
  protected IcdCategoryRelamembersService icdCategoryRelamembersService;

  @Autowired
  protected SlmServiceAgreementService slmServiceAgreementService;

  @Autowired
  protected SptSparepartService sptSparepartService;

  @Override
  public String getProceessKey() {
    return "incidentProcess";
  }

  @Override
  public IcdIncidentService getService() {
    return this.icdIncidentService;
  }

  @Override
  public String getPageTitle() {
    return "事件管理";
  }

  @RequestMapping("view")
  @Override
  public ModelAndView view(String id, HttpServletRequest req) {
    ModelAndView mv = this.getModelAndView();

    IcdIncident model = this.getService().findOne(id);
    mv.addObject("model", model);

    Map<String, Object> cusUser = this.appUserService.findOneDetailById(model
        .getCusUserId());

    mv.addObject("cusUser", cusUser);
    mv.addObject("readOnly", "true");

    return mv;
  }

  @Override
  @RequestMapping("edit")
  public ModelAndView edit(String id, HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();

    IcdIncident model = null;
    if (StringUtils.isEmpty(id)) {
      model = new IcdIncident();
      model.setId(HibernateUUIDGenerator.generate());

    } else {
      model = this.getService().findOne(id);
      mv.addObject("modelEdit", true);
      SrcServiceService srcServiceService = ContextHolder
          .getSpringBean("srcServiceService");

      ConfCiService confCiService = ContextHolder
          .getSpringBean("confCiService");

      Map<String, Object> ser = srcServiceService.findOneToMap(
          model.getServiceCategoryId(), "name");

      Map<String, Object> ci = confCiService.findOneToMap(model.getCiId(),
          "name");

      if (MapUtils.isNotEmpty(ser))
        mv.addObject("serviceCategoryName", ser.get("name"));

      if (MapUtils.isNotEmpty(ci))
        mv.addObject("ciName", ci.get("name"));

    }

    IUser user = ContextHolder.getLoginUser();
    mv.addObject("currentUserId", user.getUsername());
    mv.addObject("currentUserName", user.getFullname());

    if (StringUtils.isEmpty(model.getSupporterId())) {
      model.setSupporterId(user.getUsername());
      model.setSupporterName(user.getFullname());
    }

    if (StringUtils.isEmpty(model.getSolverId())) {
      model.setSolverId(user.getUsername());
      model.setSolverName(user.getFullname());
    }

    if (model.getResponseDate() == null) {
      model.setResponseDate(new Timestamp(new Date().getTime()));
    }

    if (model.getArrivalDate() == null) {
      model.setArrivalDate(new Timestamp(new Date().getTime()));
    }

    if (model.getSolvedDate() == null) {
      model.setSolvedDate(new Timestamp(new Date().getTime()));
    }

    mv.addObject("model", model);

    // mv.addObject("type", appDictService.findByType("USER_TYPE"));
    // 紧急
    List<AppDict> urgencys = this.appDictService.findByType("INCIDENT_URGENCY");
    // 影响
    List<AppDict> effects = this.appDictService.findByType("INCIDENT_EFFECT");
    // 级别
    List<AppDict> prioritys = this.appDictService
        .findByType("INCIDENT_PRIORITY");
    List<ProjProject> projects = this.projProjectService.findAllPublished("id",
        "name");
    // 来源
    List<AppDict> sources = this.appDictService.findByType("INCIDENT_SOURCE");

    mv.addObject("urgencys", urgencys);
    mv.addObject("effects", effects);
    mv.addObject("prioritys", prioritys);
    mv.addObject("projects", projects);
    mv.addObject("sources", sources);

    List<AppDict> solutionWays = appDictService
        .findByType("INCIDENT_SOLUTIONWAY");
    List<AppDict> solutionStatges = appDictService
        .findByType("INCIDENT_SOLUTIONSTAGE");
    mv.addObject("solutionWays", solutionWays);
    mv.addObject("solutionStages", solutionStatges);

    List<AppDict> closeCodes = appDictService.findByType("INCIDENT_CLOSECODE");
    List<AppDict> satisfications = appDictService
        .findByType("INCIDENT_SATISFICATION");

    mv.addObject("closeCodes", closeCodes);
    mv.addObject("satisfications", satisfications);

    return mv;
  }

  // ~--------------- Status Process
  protected CountQuery createStatusProcessCountQuery() {
    CountQuery cq = this.createDefaultCountQuery();

    List<AppDict> dicts = this.appDictService.findByType("INCIDENT_STATUS");

    for (AppDict d : dicts) {
      cq.addCountFilter(d.getName(), true, " status='" + d.getName() + "' ");
    }

    return cq;
  }

  // ~--------------- Status Process
  protected CountQuery createRequestPoolProcessCountQuery(String source) {
    CountQuery cq = this.createDefaultCountQuery();

    String processCondition = BpmConst
        .getQueryMyTaskSqlCondition(getProceessKey());

    cq.addCountFilter(source, true, " source='" + source + "' AND "
        + processCondition);
    cq.addCountFilter("待回访事件", true, " a.status in('待回访') ");
    cq.addCountFilter(HAVETODO_TASK, true,
        BpmConst.getQueryMyTaskAttendSqlCondition(getProceessKey()));

    cq.addCountFilter(START_TASK, true,
        BpmConst.getQueryMyTaskStartedSqlCondition(getProceessKey()));
    cq.addCountFilter(
        DRAFT_TASK,
        new StringBuffer(" ( process_id IS NULL AND  a.creator ='")
            .append(ContextHolder.getLoginUsername()).append("') ").toString());

    return cq;
  }

  @RequestMapping("statusProcessMenu")
  @ResponseBody
  public ITreeNode[] statusProcessMenu() {
    return this.createStatusProcessCountQuery().getTreeNodes();

  }

  @RequestMapping("sourceProcessMenu")
  @ResponseBody
  public ITreeNode[] sourceProcessMenu(HttpServletRequest req) {

    String sourceType = req.getParameter("sourceType");
    return this.createRequestPoolProcessCountQuery(sourceType).getTreeNodes();

  }

  @RequestMapping("statusProcessManage")
  public ModelAndView statusProcessManage() {
    return this.getModelAndView();
  }

  @RequestMapping("listStatusProcessDetail")
  @ResponseBody
  public PageResponse<Map<String, Object>> listStatusProcessDetail(
      JqGridRequest request, HttpServletRequest req) {
    return this.getListDetail(createStatusProcessCountQuery(), request, req);
  }

  @RequestMapping("listRequestPoolProcessDetail")
  @ResponseBody
  public PageResponse<Map<String, Object>> listRequestPoolProcessDetail(
      JqGridRequest request, HttpServletRequest req) {
    String source = req.getParameter("sourceType");
    return this.getListDetail(createRequestPoolProcessCountQuery(source),
        request, req);
  }

  @RequestMapping("requestPoolEdit")
  public ModelAndView requestPool(HttpServletRequest req) {

    String sourceType = req.getParameter("sourceType");

    ModelAndView mv = this.getModelAndView();
    mv.addObject("sourceType", sourceType);
    return mv;
  }

  /**
   * 流程代办的统计数
   * 
   * @return
   */
  @RequestMapping("sourceCount")
  @ResponseBody
  public Long sourceCount(HttpServletRequest req) {

    String sourceType = req.getParameter("sourceCount");

    return this.createRequestPoolProcessCountQuery(sourceType)
        .getTreeNodeCount(sourceType);

  }

  // ～--------------------------------事件监控----------------------------------

  @RequestMapping("monitorManage")
  public ModelAndView monitorManage(HttpServletRequest req) {
    return this.getModelAndView();
  }

  @RequestMapping("controlManage")
  public ModelAndView controlManage(HttpServletRequest req) {
    return this.getModelAndView();
  }

  @RequestMapping("monitorList")
  @ResponseBody
  public Page<Map<String, Object>> monitorList(JqGridRequest request,
      HttpServletRequest req) {
    request
        .setSearchString(" (close_code IS  NULL and project_id is not null and create_date>DATE_SUB(CURDATE(),INTERVAL 30 DAY) ) ");
    request.setSort("create_date", Direction.DESC);
    return this.getService().findIncidentDetails(request);
  }

  /**
   * 取得用户所在域的项目的级别统计
   * 
   * @return
   */
  @RequestMapping("getPriorityData")
  @ResponseBody
  public List<Map<String, Object>> getPriorityData() {

    List<Map<String, Object>> result = new ArrayList<>();
    List<Map<String, Object>> list = this.icdIncidentService
        .getUserIncidentGroupByPriority();

    for (Map<String, Object> map : list) {
      Map<String, Object> rMap = new HashMap<String, Object>();
      Object priority_name = map.get("priority_name");
      if (priority_name == null)
        rMap.put("label", "未设置级别");
      else
        rMap.put("label", priority_name);
      rMap.put("data", map.get("result_count"));
      result.add(rMap);
    }

    return result;
  }

  @RequestMapping("getSLAStatusData")
  @ResponseBody
  public List<Map<String, Object>> getSLAStatusData() {

    List<Map<String, Object>> result = new ArrayList<>();
    List<Map<String, Object>> list = this.icdIncidentService
        .getUserIncidentGroupBySLAStatus();

    for (Map<String, Object> map : list) {
      Map<String, Object> rMap = new HashMap<String, Object>();
      rMap.put("label", map.get("sla_status"));
      rMap.put("data", map.get("result_count"));
      result.add(rMap);
    }

    return result;
  }

  @RequestMapping("getProjectData")
  @ResponseBody
  public List<Map<String, Object>> getProjectData() {

    List<Map<String, Object>> list = this.icdIncidentService
        .getUserIncidentGroupByProject();

    return list;
  }

  @RequestMapping("getCategoryData")
  @ResponseBody
  public List<Map<String, Object>> getCategoryData() {

    List<Map<String, Object>> list = this.icdIncidentService
        .getUserIncidentGroupByCategory();

    return list;
  }

  @RequestMapping("getStatusData")
  @ResponseBody
  public List<Map<String, Object>> getStatusData() {

    List<Map<String, Object>> list = this.icdIncidentService
        .getUserIncidentGroupByStatus();

    return list;
  }

  @RequestMapping("monitorMenu")
  @ResponseBody
  public ITreeNode[] monitorMenu() {
    return this.getMonitorCountQuery().getTreeNodes("状态推移");
  }

  private CountQuery getMonitorCountQuery() {
    CountQuery cq = createDefaultCountQuery();
    List<AppDict> pStatus = appDictService.findByType("INCIDENT_STATUS");
    cq.setProjectDomain(ProjectDomain.newInstance("project_id",
        ProjectDomainType.Technology));
    for (AppDict dict : pStatus) {
      cq.addCountFilter(dict.getName(), " a.status='" + dict.getName() + "' ");
    }
    return cq;
  }

  // ～-------------------------end 事件监控------------------------------------
  protected CountQuery createMonitorSpecialCountQuery() {

    CountQuery cq = createDefaultCountQuery();
    String permissionCondition = " AND status<>'新建'  "
        + ProjectDomainUtils.getUserDomainSql(ProjectDomain
            .newInstance(ProjectDomainType.Technology));
    // 数据权限
    cq.addCountFilter("SLA超期", true, " sla_status=1 AND status<>'已关闭' "
        + permissionCondition);

    cq.addCountFilter("重大", true, " priority_name='一级'  AND status<>'已关闭' "
        + permissionCondition);

    cq.addCountFilter("挂起", true, " status IN ('挂起','挂起审核') "
        + permissionCondition);
    cq.addCountFilter(
        "多次催办",
        true,
        " status<>'已关闭' AND EXISTS (SELECT source_id FROM app_message_success WHERE \"LEVEL\"=1 AND source_id=id)  "
            + permissionCondition);

    cq.addCountFilter("VIP用户", true, " are_vip=1 AND status<>'已关闭'"
        + permissionCondition);

    cq.addCountFilter("不满意", true, "  satisfaction IN (2,1)    "
        + permissionCondition);

    cq.addCountFilter("未关闭", true, " status<>'已关闭' " + permissionCondition);

    return cq;
  }

  @RequestMapping("monitorSpecialMenu")
  @ResponseBody
  public ITreeNode[] monitorSpecialMenu() {
    return this.createMonitorSpecialCountQuery().getTreeNodes();
  }

  @RequestMapping("monitorSpecialManage")
  public ModelAndView monitorSpecialManage(HttpServletRequest req) {
    ModelAndView mv = new ModelAndView();
    mv.addObject("event_nature", appDictService.findByType("INCIDENT_NATURE"));
    return mv;
  }

  @RequestMapping("listMonitorSpecialDetail")
  @ResponseBody
  public PageResponse<Map<String, Object>> listMonitorSpecialDetail(
      JqGridRequest request, HttpServletRequest req) {
    return this.getListDetail(createMonitorSpecialCountQuery(), request, req);
  }

  // ～-------------------------end 事件监控------------------------------------

  /**
   * 获取类似事件
   * 
   * @param req
   *          jqGrid数据请求
   * @return json结果数据
   */
  @RequestMapping("searchSimilarIncidents")
  @ResponseBody
  public JqGridResponse<SolrIcdIncidentDTO> searchSimilarIncidents(
      JqGridRequest req) {

    JqGridFilter filter = req.getFilter();
    if (filter == null) {
      return null;
    }
    req.setFilters(null);// 清楚原有过滤条件
    List<JqGridFilterRule> rules = filter.getRules();

    String ciId = "", userId = "", categoryId = "", title = "";

    for (JqGridFilterRule rule : rules) {
      switch (rule.getField()) {
      case "ciId":
        ciId = rule.getData();
        break;
      case "userId":
        userId = rule.getData();
        break;
      case "categoryId":
        categoryId = rule.getData();
        break;
      case "title":
        title = rule.getData();
        break;
      }
    }

    // 返回一个分页的数据集
    Page<SolrIcdIncidentDTO> page = icdIncidentService.searchSimilarIncidents(
        ciId, userId, categoryId, title, req);
    // 返回一个符合jqgrid的json数据
    return new JqGridResponse<SolrIcdIncidentDTO>(page);

  }

  // 根据标题查找类似事件For前端
  @RequestMapping("searchSimilarIncidentsByTitle")
  @ResponseBody
  public JqGridResponse<SolrIcdIncidentDTO> searchSimilarIncidentsByTitle(
      String title) {

    JqGridRequest req = new JqGridRequest();
    req.setFilters(null);// 清楚原有过滤条件
    req.setRows(5);
    // 返回一个分页的数据集
    Page<SolrIcdIncidentDTO> page = icdIncidentService.searchSimilarIncidents(
        "", "", "", title, req);

    // 返回一个符合jqgrid的json数据
    return new JqGridResponse<SolrIcdIncidentDTO>(page);

  }

  /**
   * 向导式创建页面
   * 
   * @param req
   *          http请求
   * @return 向导式创建页面
   */
  @RequestMapping("wizCreateEdit")
  public ModelAndView wizCreateEdit(HttpServletRequest req) {

    ModelAndView mv = new ModelAndView("incident/incident/wizCreateEdit");
    mv.addObject("id", HibernateUUIDGenerator.generate());
    mv.addObject("currentUserId", ContextHolder.getLoginUsername());
    mv.addObject("currentUserName", ContextHolder.getLoginUser().getFullname());

    return mv;

  }

  /**
   * 普通创建事件单
   * 
   * @param req
   *          http请求
   * @return 普通创建事件单界面
   * @throws Exception
   */
  @RequestMapping("newIncidentEdit")
  public ModelAndView newIncidentEdit(String id, HttpServletRequest request)
      throws Exception {

    ModelAndView mv = new ModelAndView("incident/incident/newIncidentEdit");
    IcdIncident model = null;

    if (StringUtils.isNotEmpty(id)) {

      model = this.getService().findOne(id);
      mv.addObject("cus_user_id", model.getCusUserId());

      mv.addObject("modelEdit", true);
      SrcServiceService srcServiceService = ContextHolder
          .getSpringBean("srcServiceService");

      ConfCiService confCiService = ContextHolder
          .getSpringBean("confCiService");

      Map<String, Object> ser = srcServiceService.findOneToMap(
          model.getServiceCategoryId(), "name");

      Map<String, Object> ci = confCiService.findOneToMap(model.getCiId(),
          "name", "code", "asset_code");

      if (MapUtils.isNotEmpty(ser))
        mv.addObject("serviceCategoryName", ser.get("name"));

      if (MapUtils.isNotEmpty(ci)) {
        mv.addObject("ciName", ci.get("name"));
        mv.addObject("ciAssetCode", ci.get("asset_code"));
      }

    } else {
      model = new IcdIncident();
      model.setId(HibernateUUIDGenerator.generate());
      Timestamp d = new Timestamp(System.currentTimeMillis());
      model.setSolvedDate(d);
      model.setHappenTime(d);

    }

    String openid = request.getParameter("openid");
    if (StringUtils.isNotEmpty(openid)) {

      mv.addObject("openid", openid);
      // 自动关联用户
      AppUser u = appUserService.findByOpenid(openid, "id");
      mv.addObject("cus_user_id", u.getId());
      mv.addObject("source", "微信");
      //
      WechatChatService wechatChatService = ContextHolder
          .getSpringBean("wechatChatService");

      wechatChatService.relationToObject(openid, model.getId());

      // List<WechatChat> chats = wechatChatService
      // .findNotRelationByOpenid(id);

    }

    String caller = request.getParameter("caller");
    mv.addObject("caller", caller);

    String cusUserId = request.getParameter("cusUserId");
    if (StringUtils.isNotEmpty(cusUserId)) {
      mv.addObject("cus_user_id", cusUserId);
      // 设置用户信息
      model.setCusUserId(cusUserId);
      model.setDescription(request.getParameter("description"));

    }
    List<AppDict> satisfications = appDictService
        .findByType("INCIDENT_SATISFICATION");

    mv.addObject("satisfications", satisfications);
    mv.addObject("model", model);
    mv.addObject("type", appDictService.findByType("USER_TYPE"));

    mv.addObject("pageTitle", "");
    return mv;

  }

  /**
   * 事件分派
   * 
   * @param id
   *          唯一标识
   * @param req
   *          http 请求
   * @return 事件分派界面
   */
  @RequestMapping("assignEdit")
  public ModelAndView assignEdit(String id, HttpServletRequest req) {

    ModelAndView mv = new ModelAndView("incident/incident/assignEdit");

    IcdIncident model = this.getService().findOne(id);

    if (StringUtils.isEmpty(model.getSource())) {
      // 默认事件来源为电话
      model.setSource(appDictService.getInitStatus("INCIDENT_SOURCE"));
    }

    Map<String, Object> cusUser = this.appUserService.findOneDetailById(model
        .getCusUserId());

    // 紧急
    List<AppDict> urgencys = this.appDictService.findByType("INCIDENT_URGENCY");
    // 影响
    List<AppDict> effects = this.appDictService.findByType("INCIDENT_EFFECT");
    // 级别
    List<AppDict> prioritys = this.appDictService
        .findByType("INCIDENT_PRIORITY");

    List<ProjProject> projects = this.projProjectService.findAllPublished("id",
        "name");

    // 来源
    List<AppDict> sources = this.appDictService.findByType("INCIDENT_SOURCE");

    if (StringUtils.isEmpty(model.getIcdCategoryId())
        && StringUtils.isNotEmpty(model.getCiId())) {
      // 根据ciId获取其所关联的ci分类的名称
      // 根据ci分类名称查询事件分类，然后设置到事件单的值
      IcdCategory cate = this.getService().getCategoryByCiId(model.getCiId());
      if (cate != null) {
        model.setIcdCategoryId(cate.getId());
        model.setIcdCategoryName(cate.getTreenodeNamePath());
      }

    }
    List<AppDict> satisfications = appDictService
        .findByType("INCIDENT_SATISFICATION");
    mv.addObject("satisfications", satisfications);
    mv.addObject("model", model);
    mv.addObject("cusUser", cusUser);

    mv.addObject("urgencys", urgencys);
    mv.addObject("effects", effects);
    mv.addObject("prioritys", prioritys);
    mv.addObject("projects", projects);
    mv.addObject("sources", sources);

    Map<String, Object> relationIncident = this.getService().findOneDetailById(
        id);

    mv.addObject("relationIncident", relationIncident);

    return mv;
  }

  /**
   * 事件处理
   * 
   * @param id
   *          唯一标识
   * @param req
   *          http请求
   * @return 事件受理界面
   */
  @RequestMapping("acceptEdit")
  public ModelAndView acceptEdit(String id, HttpServletRequest req) {

    ModelAndView mv = new ModelAndView("incident/incident/acceptEdit");

    IcdIncident model = this.getService().findOne(id);

    Map<String, Object> cusUser = this.appUserService.findOneDetailById(model
        .getCusUserId());

    mv.addObject("cusUser", cusUser);

    Map<String, Object> relationIncident = this.getService().findOneDetailById(
        id);

    mv.addObject("relationIncident", relationIncident);

    IUser user = ContextHolder.getLoginUser();
    model.setSolverName(user.getFullname());
    model.setSolverId(user.getUsername());

    model.setSolvedDate(new Timestamp(System.currentTimeMillis()));

    mv.addObject("model", model);

    List<String> words;
    try {
      words = itsm.isperp.framework.utils.StringUtils.tokenizer(model
          .getTitle().replaceAll("\\pP", ""));

      String wordsStr = "";
      int wsize = words.size();
      if (wsize > 1) {
        wordsStr = "'" + words.get(0) + "'";
      }
      for (int i = 1; i < wsize; i++) {
        wordsStr += ",'" + words.get(i) + "'";
      }

      mv.addObject("words", wordsStr);

      mv.addObject("highlight", true);
    } catch (Exception e) {

    }

    return mv;
  }

  @RequestMapping("development/form1Edit")
  public ModelAndView form1Edit(String id, HttpServletRequest req) {

    ModelAndView mv = new ModelAndView();
    IcdIncident model = this.getService().findOne(id);
    Map<String, Object> cusUser = this.appUserService.findOneDetailById(model
        .getCusUserId());
    mv.addObject("cusUser", cusUser);
    mv.addObject("model", model);
    return mv;
  }

  @RequestMapping("development/form3Edit")
  public ModelAndView form3Edit(String id, HttpServletRequest req) {

    ModelAndView mv = new ModelAndView();
    IcdIncident model = this.getService().findOne(id);
    Map<String, Object> cusUser = this.appUserService.findOneDetailById(model
        .getCusUserId());
    mv.addObject("cusUser", cusUser);
    mv.addObject("model", model);
    return mv;
  }

  /**
   * 事件处理
   * 
   * @param id
   *          唯一标识
   * @param req
   *          http请求
   * @return 事件处理界面
   */
  @RequestMapping("handleEdit")
  public ModelAndView handleEdit(String id, HttpServletRequest req) {
    ModelAndView mv = new ModelAndView("incident/incident/handleEdit");
    IcdIncident model = this.getService().findOne(id);
    Map<String, Object> cusUser = this.appUserService.findOneDetailById(model
        .getCusUserId());
    mv.addObject("cusUser", cusUser);
    Map<String, Object> relationIncident = this.getService().findOneDetailById(
        id);
    mv.addObject("relationIncident", relationIncident);
    List<AppDict> solutionWays = appDictService
        .findByType("INCIDENT_SOLUTIONWAY");
    List<AppDict> solutionStatges = appDictService
        .findByType("INCIDENT_SOLUTIONSTAGE");
    IUser user = ContextHolder.getLoginUser();
    model.setSolverName(user.getFullname());
    model.setSolverId(user.getUsername());
    model.setSolvedDate(new Timestamp(System.currentTimeMillis()));
    
    String categoryId=model.getServiceCategoryId();
    if(StringUtils.isNoneBlank(categoryId))
    {
      SrcServiceService srcServiceService= ContextHolder.getSpringBean("srcServiceService");
      SrcService srcService=srcServiceService.findOne(categoryId);
      model.setTimeCost(srcService.getStandardCost());
    }
    mv.addObject("model", model);
    mv.addObject("solutionWays", solutionWays);
    mv.addObject("solutionStages", solutionStatges);
    return mv;
  }

  /**
   * 事件处理
   * 
   * @param id
   *          唯一标识
   * @param req
   *          http请求
   * @return IT担当确认工时审核视图
   */
  @RequestMapping("handleEdit2")
  public ModelAndView handleEdit2(String id, HttpServletRequest req) {

    ModelAndView mv = new ModelAndView("incident/incident/handleEdit2");

    IcdIncident model = this.getService().findOne(id);

    Map<String, Object> cusUser = this.appUserService.findOneDetailById(model
        .getCusUserId());

    mv.addObject("cusUser", cusUser);

    List<AppDict> solutionWays = appDictService
        .findByType("INCIDENT_SOLUTIONWAY");
    List<AppDict> solutionStatges = appDictService
        .findByType("INCIDENT_SOLUTIONSTAGE");

    mv.addObject("model", model);
    mv.addObject("solutionWays", solutionWays);
    mv.addObject("solutionStages", solutionStatges);
    model.setSolvedDate(new Timestamp(System.currentTimeMillis()));
    model.setCloserId(ContextHolder.getLoginUsername());
    List<AppDict> closeCodes = appDictService.findByType("INCIDENT_CLOSECODE");
    List<AppDict> satisfications = appDictService
        .findByType("INCIDENT_SATISFICATION");

    mv.addObject("closeCodes", closeCodes);
    mv.addObject("satisfications", satisfications);

    List<String> words;
    try {
      words = itsm.isperp.framework.utils.StringUtils.tokenizer(model
          .getTitle().replaceAll("\\pP", ""));

      String wordsStr = "";
      int wsize = words.size();
      if (wsize > 1) {
        wordsStr = "'" + words.get(0) + "'";
      }
      for (int i = 1; i < wsize; i++) {
        wordsStr += ",'" + words.get(i) + "'";
      }

      mv.addObject("words", wordsStr);

      mv.addObject("highlight", true);
    } catch (Exception e) {

    }

    return mv;
  }

  /**
   * 事件关闭
   * 
   * @param id
   *          事件唯一标识
   * @param req
   *          http请求
   * @return 事件关闭界面
   */
  @RequestMapping("closeEdit")
  public ModelAndView closeEdit(String id, HttpServletRequest req) {

    ModelAndView mv = new ModelAndView("incident/incident/closeEdit");

    IcdIncident model = this.getService().findOne(id);

    model.setSatisfaction(4); // 满意度默认为4分

    Map<String, Object> cusUser = this.appUserService.findOneDetailById(model
        .getCusUserId());

    mv.addObject("cusUser", cusUser);

    Map<String, Object> relationIncident = this.getService().findOneDetailById(
        id);

    model.setSolvedDate(new Timestamp(System.currentTimeMillis()));
    model.setCloserId(ContextHolder.getLoginUsername());
    List<AppDict> closeCodes = appDictService.findByType("INCIDENT_CLOSECODE");
    List<AppDict> satisfications = appDictService
        .findByType("INCIDENT_SATISFICATION");

    mv.addObject("closeCodes", closeCodes);
    mv.addObject("satisfications", satisfications);

    mv.addObject("model", model);
    mv.addObject("relationIncident", relationIncident);
    return mv;
  }

  @RequestMapping("deal")
  @ResponseBody
  public ResultMessage deal(String id, String type, HttpServletRequest req)
      throws SQLException {

    if (StringUtils.isEmpty(id)) {
      return ResultMessage.failure("id不能为空");
    }
    IcdIncident model = new IcdIncident();
    model.setId(id);

    Set<String> includeColumns = new HashSet<>();
    includeColumns.add("status");
    // 响应
    if ("3".equals(type)) {
      model.setStatus("已响应");
      model.setResponserId(ContextHolder.getLoginUsername());
      model.setResponseDate(new Timestamp(new Date().getTime()));
      // 更新状态机响应时间字段
      includeColumns.add("response_date");
      includeColumns.add("responser_id");
    } else if ("4".equals(type)) {
      model.setStatus("已到场");
      // 更新状态机响应时间字段
      model.setArrivalDate(new Timestamp(new Date().getTime()));
      model.setArriverId(ContextHolder.getLoginUsername());
      includeColumns.add("arrival_date");
      includeColumns.add("arriver_id");
    }

    this.getService().dynamicUpdateSpecific(model, includeColumns);
    slmServiceAgreementService.elapsedWorktime(60);
    return ResultMessage.success();
  }

  @RequestMapping("saveAndStart")
  @ResponseBody
  public ResultMessage saveAndStart(IcdIncident model, String type,
      HttpServletRequest req) throws SQLException {

    model.setStatus("已分派");
    model.setCreateDate(new Timestamp(new java.util.Date().getTime()));
    this.icdIncidentService.saveOrUpdateAndSpecific(model, req, "status",
        "createDate");

    bpmProcessRunService.startProcess(ContextHolder.getLoginUsername(),
        this.getProceessKey(), model.getId(), null);

    String formUrl = bpmProcessRunService.entry(model.getId(),
        this.getProceessKey(), null);

    if ("2".equals(type)) {
      return ResultMessage.success("incident/incident/edit");
    }

    return ResultMessage.success(formUrl);

  }

  @RequestMapping("saveAndFinish")
  @ResponseBody
  public ResultMessage saveAndFinish(IcdIncident model, String processId,
      HttpServletRequest req) throws SQLException {

    model.setStatus("已关闭");
    model.setClosedDate(new Date());
    this.getService().saveOrUpdate(model, req);
    bpmProcessRunService.deleteProcessInstance(processId, "解决并关闭",
        ContextHolder.getLoginUsername());
    return ResultMessage.success();

  }

  @RequestMapping("approvalEdit")
  public ModelAndView approvalEdit(String id, HttpServletRequest req) {
    ModelAndView mv = this.view(id, req);
    mv.setViewName("incident/incident/approvalEdit");

    return mv;

  }

  @RequestMapping("listByCusUser")
  @ResponseBody
  public Page<IcdIncident> listByCusUser(String id, String cusUserId,
      JqGridRequest request, HttpServletRequest req) {

    String all = req.getParameter("all");
    if (StringUtils.isEmpty(all)) {

      return this.getService().findClosedIncidentByCusUserId(id, cusUserId,
          request);
    } else {
      return this.getService().findAllIncidentByCusUserId(id, cusUserId,
          request);
    }
  }

  @RequestMapping("listHandleProcess")
  @ResponseBody
  public List<IcdIncidentHandleProcess> listHandleProcess(String relationId) {

    if (StringUtils.isEmpty(relationId)) {
      return null;
    }

    IcdIncidentHandleProcessService icdIncidentHandleProcessService = ContextHolder
        .getSpringBean("icdIncidentHandleProcessService");
    JqGridRequest req = new JqGridRequest();
    req.isPageable(false);
    req.addFilterRule("relation_id", JqGridFilterRuleOp.eq, relationId);
    return icdIncidentHandleProcessService.findAll(req).getContent();

  }

  @RequestMapping("doUpdateicdTime")
  @ResponseBody
  public String doUpdateicdTime(HttpServletRequest req) throws ParseException {
    String code = req.getParameter("code");
    String createTime = req.getParameter("createTime");
    // String responseTime=req.getParameter("responseTime");
    // String arriveTime=req.getParameter("arriveTime");
    // String solveTime=req.getParameter("solveTime");
    String closeTime = req.getParameter("closeTime");
    try {
      SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
      Date createDate = sFormat.parse(createTime);
      Date closeDate = null;
      if (StringUtils.isNotEmpty(closeTime)) {
        closeDate = sFormat.parse(closeTime);
      }

      this.getService().doUpdateTime(code,createDate);
      return "成功";
    } catch (Exception e) {
      return "异常";
    }

  }

  @RequestMapping("checkDelete")
  @ResponseBody
  public ResultMessage checkDelete(HttpServletRequest req, String id)
      throws ParseException {
    return this.getService().checkDelete(id);
  }

  @RequestMapping("updateicdEdit")
  public ModelAndView updateicdTime(String id, HttpServletRequest req) {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("incident/incident/updateicdEdit");
    return mv;

  }

  @RequestMapping("Test")
  @ResponseBody
  public ResultMessage Test(HttpServletRequest req, String id) {

    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    String sql1 = "SELECT * FROM per_performance WHERE create_date<'2017-12-14' AND STATUS<>'已完成' AND CODE NOT IN('PER20171213072','PER20171213071','PER20171213070','PER20171213069') AND STATUS='自评分'";
    String username = ContextHolder.getLoginUsername();

    String sql3 = "SELECT * FROM per_performance WHERE create_date<'2017-12-01' and create_date>'2017-11-01' AND STATUS<>'已完成' AND CODE NOT IN('PER20171213072','PER20171213071','PER20171213070','PER20171213069','PER20171202005')  AND STATUS='退回'";
    List<Map<String, Object>> list3 = jdbcTemplate.queryForList(sql3);
    for (Map<String, Object> m3 : list3) {
      String processId = m3.get("process_id").toString();
      bpmProcessRunService.jumpto(processId,
          "sid-3837FD60-55E2-472A-85B5-15316FCDA961",
          "sid-3837FD60-55E2-472A-85B5-15316FCDA961", "");
    }

    return ResultMessage.newInstance(true, "");
  }

  @RequestMapping("getIcdData")
  @ResponseBody
  public List<IcdIncident> getIcdData(HttpServletRequest req,
      JqGridRequest request) throws Exception {
    request.setSelectColumns("a.*,b.name as project_name");
    request
        .setSearchString("a.status<>'已关闭' and a.status<>'待回访' and a.supporter_name is not null and a.supporter_name<>'' and b.name is not null");
    DataResponse<IcdIncident> icd = this.getService().getRepository()
        .findProjectByRequest(request);
    return icd;
  }

  @RequestMapping("getReportIcd")
  @ResponseBody
  public PageResponse<Map<String, Object>> getReportIcd(HttpServletRequest req,
      JqGridRequest request, String date, String fullname, String type)
      throws Exception {
    SimpleDateFormat sft = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy",
        Locale.UK);
    SimpleDateFormat sft1 = new SimpleDateFormat("yyyy-MM-dd");
    Date temp = sft.parse(date);
    String reportDate = sft1.format(temp);
    request.setSearchString("fullname = '" + fullname
        + "' and report_date like '%" + reportDate + "%'");
    PageResponse<Map<String, Object>> icd = null;

    switch (type) {
    case "1":
      icd = this.getService().getRepository().findOrderIncident(request)
          .toPage();
      break;
    case "2":
      icd = this.getService().getRepository().findCheckinIncident(request)
          .toPage();
      break;
    case "3":
      icd = this.getService().getRepository().findSolutionIncident(request)
          .toPage();
      break;
    case "4":
      icd = this.getService().getRepository().findNotFinishIncident(request)
          .toPage();
      break;
    }

    return icd;
  }

  @RequestMapping("viewMail")
  public ModelAndView viewMail(String id, HttpServletRequest req) {
    ModelAndView mv = new ModelAndView("incident/incident/viewMail");
    IcdIncident model = this.getService().findOne(id);
    mv.addObject("model", model);
    return mv;
  }

  @RequestMapping("startUpProcess")
  @ResponseBody
  public String startUpProcess() {
    this.getService().startIcd();
    return "ok";
  }
  
  @RequestMapping("startUpProbProcess")
  @ResponseBody
  public String startUpProbProcess() {
    this.getService().startProb();
    return "ok";
  }
  
  @RequestMapping("gtnext")
  @ResponseBody
  public String gtnext(String tableName,String processKey,String nextTaskId,String nextTransitionId,String status,String  handColumn) {
    this.getService().gotoNextStep(tableName,processKey,nextTaskId, nextTransitionId, status, handColumn);
    return "ok";
  }
}
